package com.yjf.ljr.util;

import com.yjf.ljr.R;
import com.yjf.ljr.activity.ConfirmationTransferActivity;
import com.yjf.ljr.common.CommonData;
import com.yjf.ljr.connection.IjConnect;
import com.yjf.ljr.dataclass.AppinvestDataClass;
import com.yjf.ljr.dataclass.TransferSubmitDataClass;
import com.yjf.ljr.parser.RequestBuilder;
import com.yjf.ljr.parser.RequestBuilder.RequestObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Build;
import android.os.StrictMode;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class AppTransferDialog extends Dialog {

	public AppTransferDialog(Context context) {
		super(context);

	}

	public AppTransferDialog(Context context, int theme) {
		super(context, theme);
	}

	public static class Builder {
		private Context context;
		private String title;
		private String paypassUrl;
		// private CookieManager mCookieManager;
		private String token;
		private String tradeId;// 当前项目的tradeID
		private String demandId;// 项目ID

		// add red packet and experience amount
		private String giftMoney;// 红包
		private String experienceAmount;// 体验金

		private String positiveButtonText;
		private String negativeButtonText;
		private View contentView;
		private ProgressBar mProgressBar;
		// private LinearLayout mLayoutInvestPayBlank;
		private WebView mwebView;
		private LinearLayout mLlTitleyjfPaypassUrl;
		private DialogInterface.OnClickListener positiveButtonClickListener;
		private DialogInterface.OnClickListener negativeButtonClickListener;
		private boolean resultFlag = false;
		private CookieManager mCookieManager;
		private String paytk;// 支付令牌
		private String tradeDetailId;// 查询Id
		private String amount;// 转让金额
		private LinearLayout mLayoutInvestPayBlank;

		private boolean showProgress = false;

		public Builder(Context context) {
			this.context = context;

		}

		public Builder setTradeDetailId(int tradeDetailId) {
			this.tradeDetailId = (String) context.getText(tradeDetailId);
			return this;
		}

		public Builder setTradeDetailId(String tradeDetailId) {
			this.tradeDetailId = tradeDetailId;
			return this;
		}

		public Builder setPaypassUrl(String paypassUrl) {
			this.paypassUrl = paypassUrl;
			resultFlag = false;
			return this;
		}

		/**
		 * Set the Dialog message from resource
		 * 
		 * @param title
		 * @return
		 */
		public Builder setPaypassUrl(int paypassUrl) {
			this.paypassUrl = (String) context.getText(paypassUrl);
			return this;
		}

		public Builder setAmount(String amount) {
			this.amount = amount;
			return this;
		}

		public Builder setAmount(int amount) {
			this.amount = (String) context.getText(amount);
			return this;
		}

		public Builder setToken(String token) {
			this.token = token;

			return this;
		}

		public Builder setToken(int token) {
			this.token = (String) context.getText(token);
			return this;
		}

		public Builder setTradeId(String tradeId) {
			this.tradeId = tradeId;

			return this;
		}

		public Builder setTradeId(int tradeId) {
			this.tradeId = (String) context.getText(tradeId);
			return this;
		}

		public Builder setDemandId(String demandId) {
			this.demandId = demandId;

			return this;
		}

		public Builder setDemandId(int demandId) {
			this.demandId = (String) context.getText(demandId);
			return this;
		}

		/**
		 * set red packet amount
		 * 
		 * @param giftMoney
		 * @return
		 */
		public Builder setGiftMoney(String giftMoney) {
			this.giftMoney = giftMoney;
			return this;
		}

		/**
		 * set experience amount
		 * 
		 * @param experienceAmount
		 * @return
		 */
		public Builder setExperienceAmount(String experienceAmount) {
			this.experienceAmount = experienceAmount;
			return this;
		}

		/**
		 * Set the Dialog title from resource
		 * 
		 * @param title
		 * @return
		 */
		public Builder setTitle(int title) {
			this.title = (String) context.getText(title);
			return this;
		}

		/**
		 * Set the Dialog title from String
		 * 
		 * @param title
		 * @return
		 */

		public Builder setTitle(String title) {
			this.title = title;
			return this;
		}

		public Builder setContentView(View v) {
			this.contentView = v;
			return this;
		}

		/**************** 得到屏幕高度 *******************/

		/**
		 * Set the positive button resource and it's listener
		 * 
		 * @param positiveButtonText
		 * @return
		 */
		public Builder setPositiveButton(int positiveButtonText, DialogInterface.OnClickListener listener) {
			this.positiveButtonText = (String) context.getText(positiveButtonText);
			this.positiveButtonClickListener = listener;
			return this;
		}

		public Builder setPositiveButton(String positiveButtonText, DialogInterface.OnClickListener listener) {
			this.positiveButtonText = positiveButtonText;
			this.positiveButtonClickListener = listener;
			return this;
		}

		public Builder setNegativeButton(int negativeButtonText, DialogInterface.OnClickListener listener) {
			this.negativeButtonText = (String) context.getText(negativeButtonText);
			this.negativeButtonClickListener = listener;
			return this;
		}

		public Builder setNegativeButton(String negativeButtonText, DialogInterface.OnClickListener listener) {
			this.negativeButtonText = negativeButtonText;
			this.negativeButtonClickListener = listener;
			return this;
		}

		String cookieString;

		@SuppressLint({ "SetJavaScriptEnabled", "NewApi" })
		public AppTransferDialog create() {
			showProgress = false;
			/***************************/
			if (Build.VERSION.SDK_INT >= 11) {
				StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites()
						.detectNetwork().penaltyLog().build());
				StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectLeakedSqlLiteObjects()
						.detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());
			}

			/***************************/

			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			// instantiate the dialog with the custom Theme
			final AppTransferDialog dialog = new AppTransferDialog(context, R.style.Dialog);
			View layout = inflater.inflate(R.layout.activity_appinvest_dialog, null);
			dialog.addContentView(layout, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
			// set the dialog title
			((TextView) layout.findViewById(R.id.tvAppInvesttitle)).setText(title);
			mwebView = ((WebView) layout.findViewById(R.id.wvAppInvestPaymentCipher));
			mLayoutInvestPayBlank = (LinearLayout) layout.findViewById(R.id.llInvest_pay_blank);
			mLlTitleyjfPaypassUrl = (LinearLayout) layout.findViewById(R.id.llTitleyjfPaypassUrl);
			mLlTitleyjfPaypassUrl.setVisibility(View.GONE);

			mProgressBar = ((ProgressBar) layout.findViewById(R.id.appInvestprogressBar));
			// set the confirm button
			if (positiveButtonText != null) {
				((Button) layout.findViewById(R.id.positiveButton)).setText(positiveButtonText);
				if (positiveButtonClickListener != null) {
					((Button) layout.findViewById(R.id.positiveButton)).setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
							positiveButtonClickListener.onClick(dialog, DialogInterface.BUTTON_POSITIVE);
						}
					});
				}
			} else {
				// if no confirm button just set the visibility to GONE
				layout.findViewById(R.id.positiveButton).setVisibility(View.GONE);
			}
			// set the cancel button
			if (negativeButtonText != null) {
				((Button) layout.findViewById(R.id.negativeButton)).setText(negativeButtonText);
				if (negativeButtonClickListener != null) {
					((Button) layout.findViewById(R.id.negativeButton)).setOnClickListener(new View.OnClickListener() {
						public void onClick(View v) {
							negativeButtonClickListener.onClick(dialog, DialogInterface.BUTTON_NEGATIVE);
						}
					});
				}
			} else {
				// if no confirm button just set the visibility to GONE
				layout.findViewById(R.id.negativeButton).setVisibility(View.GONE);
			}

			// set the content message
			if (paypassUrl != null) {

				WebSettings settings = mwebView.getSettings();
				mwebView.loadUrl(paypassUrl);

				int scale = (int) context.getResources().getDimension(R.dimen.webview_scale);
				mwebView.setInitialScale(scale);
				mwebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
				settings.setSupportZoom(false);
				settings.setBuiltInZoomControls(false);
				settings.setDomStorageEnabled(true);

				settings.setAllowFileAccess(true);

				settings.setAppCacheEnabled(true);

				settings.setJavaScriptEnabled(true);
				mwebView.getSettings().setUseWideViewPort(true);
				settings.setCacheMode(WebSettings.LOAD_DEFAULT);

				settings.setUseWideViewPort(false);
				settings.setLoadWithOverviewMode(false);
				settings.supportMultipleWindows();
				settings.setDatabaseEnabled(true);
				CookieSyncManager.createInstance(context);
				settings.setJavaScriptCanOpenWindowsAutomatically(true);

				/*******************/
				mwebView.setWebChromeClient(new WebChromeClient());

				mwebView.setWebViewClient(new WebViewClient() {

					@Override
					public void onPageFinished(WebView view, String url) {
						// TODO Auto-generated method stub

						int pagefinishResult = url.indexOf("isSuccess=true");
						resultFlag = true;

						if (!showProgress) {
							mProgressBar.setVisibility(View.GONE);
							mLayoutInvestPayBlank.setVisibility(View.GONE);
						}

						mwebView.clearCache(true);
						mwebView.clearHistory();
						super.onPageFinished(view, url);

					}

					@Override
					public void onPageStarted(WebView view, String url, Bitmap favicon) {
						// TODO Auto-generated method stub
						super.onPageStarted(view, url, favicon);

						mProgressBar.setVisibility(View.VISIBLE);
						mLayoutInvestPayBlank.setVisibility(View.VISIBLE);
						int cancelResult = url.indexOf("yjfPayPassewordCancelUrl");
						int ReturnResult = url.indexOf("yjfPayPassewordReturnUrl");
						int determineResult = url.indexOf("isSuccess=true");
						String mFailStr = null;
						AppinvestDataClass dc = new AppinvestDataClass();
						if (-1 != cancelResult && -1 == ReturnResult && resultFlag) {
							dialog.dismiss();

						} else if (-1 != determineResult && -1 == cancelResult) {
							showProgress = true;
							mProgressBar.setVisibility(View.VISIBLE);

							String paytk = "";
							int endIndex = url.indexOf("&_t");
							int startIndex = url.indexOf("paytk=");
							if (!TextUtils.isEmpty(url) && endIndex != -1) {

								// TODO Auto-generated method stub
								resultFlag = true;
								paytk = url.substring(startIndex + 6, endIndex).toString();
								mwebView.stopLoading();
								// new InvestPasswordTask(tradeId, demandId,
								// paytk, token, amount, giftMoney,
								// experienceAmount, dialog).execute();
								new TransferSubmitTask(paytk, amount, tradeDetailId, dialog).execute();

							}
						}
					}
				});

			} else if (contentView != null) {
				// if no message set // add the contentView to the dialog body
				((WebView) layout.findViewById(R.id.wvAppInvestPaymentCipher)).removeAllViews();
				((WebView) layout.findViewById(R.id.wvAppInvestPaymentCipher)).addView(contentView,
						new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
			}

			dialog.setContentView(layout);
			dialog.setCanceledOnTouchOutside(false);
			return dialog;
		}

		class TransferSubmitTask extends AsyncTask<Void, Void, Void> {

			private AppTransferDialog dialog;
			private String paytk;
			private String amount;
			private String tradeDetailId;

			private String mFailStr;
			private TransferSubmitDataClass dc = new TransferSubmitDataClass();

			public TransferSubmitTask(String paytk, String amount, String tradeDetailId, AppTransferDialog dialog) {

				this.dialog = dialog;
				this.paytk = paytk;
				this.amount = amount;
				this.tradeDetailId = tradeDetailId;
			}

			@Override
			protected Void doInBackground(Void... params) {
				RequestObject requestObject = new RequestObject();
				requestObject.method = "transferSubmit";
				requestObject.map.put("paytk", paytk);
				requestObject.map.put("tradeDetailId", tradeDetailId);
				requestObject.map.put("amount", amount);
				// add red packet and experience amount

				String requrestUrl = RequestBuilder.build(requestObject);
				try {
					IjConnect.doRequest(requrestUrl, dc);

					if (dc.code == null) {
						mFailStr = "获取数据异常，请稍后重试";
					} else if (!dc.code.equals(CommonData.RESULT_SUCCESS)) {
						mFailStr = dc.msg;
					}
				} catch (Exception e) {
					mFailStr = "获取数据异常，请稍后重试";
					e.printStackTrace();
				}

				return null;
			}

			@Override
			protected void onPostExecute(Void result) {
				// TODO Auto-generated method stub
				super.onPostExecute(result);
				if (!(TextUtils.isEmpty(mFailStr))) {// fail
					Toast.makeText(context, mFailStr, Toast.LENGTH_LONG).show();
					dialog.dismiss();
				} else {// success
					Toast.makeText(context, dc.msg, Toast.LENGTH_LONG).show();
					dialog.dismiss();
					ConfirmationTransferActivity.mDialogTransfering.show();

				}
			}

		}

	}

}
